import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import contractApi from "@/api/contractApi.ts";
import {Contract} from "@/types/resp/contract";
import CandidateSelector from "@/pages/candidate/CandidateSelector.tsx";

interface ContractAddProps {
  visible: boolean;
  id: number;
  onCloseContractAdd: () => void;
}

const ContractAdd: React.FC<ContractAddProps> = ({visible, id, onCloseContractAdd}) => {

  const [form] = Form.useForm<Contract>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    candidateName: [
      { required: true, message: '请输入应聘者姓名' }
    ],
    contractSignDate: [
      { required: true, message: '请输入合同签订日期' }
    ],
    contractType: [
      { required: true, message: '请输入合同类型' }
    ],
    state: [
      { required: true, message: '请输入合同状态' }
    ],
    jobDescription: [
      { required: true, message: '请输入岗位职责' }
    ],
  };

  let contractForm: Partial<Contract> = {}

  const [title, setTitle] = useState('新增劳动合同信息');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑劳动合同信息')
      initContractFormById(id)
    } else {
      setTitle('新增劳动合同信息')
      form.resetFields();
    }
  }, [visible]);

  const initContractFormById = async (id: number) => {
    const resp: Result<Contract> = await contractApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      contractForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let contract2Save:Contract = form.getFieldsValue()
      if (id) {
        contract2Save = Object.assign(contractForm, contract2Save)
      }
      const resp: Result<void> = await contractApi.save(contract2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增劳动合同信息')
    form.resetFields();
  };
  
  const [candidateSelectorVisible, setCandidateSelectorVisible] = useState(false);
  const findCandidate = () => {
    setCandidateSelectorVisible(true);
  }
  const handleCandidateSelected = (selectedCandidate: { candidateId?: number; candidateName?: string; }) => {
    setCandidateSelectorVisible(false)
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      candidateId: selectedCandidate['candidateId'],
      candidateName: selectedCandidate['candidateName'],
      }));
    }
  };
  const handleCloseCandidateSelector = () => {
    setCandidateSelectorVisible(false)
  };

  const onBack = () => {
    onCloseContractAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseContractAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="contractForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="candidateName" label="应聘者姓名"  rules={rules.candidateName}>
              <Input.Search placeholder="请选择应聘者姓名" onSearch={findCandidate} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="contractSignDate" label="合同签订日期" rules={rules.contractSignDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="contractType" label="合同类型" rules={rules.contractType}>
              <Select placeholder="请选择合同类型" options={[
                { value: 10, label: <span>全职</span> },
                { value: 20, label: <span>兼职</span> },
                { value: 30, label: <span>实习</span> }
              ]} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="effectiveDate" label="生效日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="expiryDate" label="到期日期">
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="state" label="合同状态" rules={rules.state}>
              <Select placeholder="请选择合同状态" options={[
                { value: 10, label: <span>有效</span> },
                { value: 20, label: <span>终止</span> },
                { value: 30, label: <span>续签</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="workLocation" label="工作地点">
              <Input maxLength={255} placeholder="请输入工作地点"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="workingHours" label="工作时间">
              <Input maxLength={255} placeholder="请输入工作时间"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={22}>
            <Form.Item name="jobDescription" label="岗位职责" labelCol={{span: 3}} rules={rules.jobDescription}>
              <Input.TextArea maxLength={65535} placeholder="请输入岗位职责" autoSize={{ minRows: 3, maxRows: 3 }}/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <CandidateSelector visible={candidateSelectorVisible} onCandidateSelected={handleCandidateSelected} onCloseCandidateSelector={handleCloseCandidateSelector} />
    </Modal>
  )
}

export default ContractAdd;
